package math;

/**
 * 封装数学题的构建类
 */
public class MathProblemBuilder {
    //难度 0代表三年级难度，1代表四年级难度，2代表五年级难度
    private int difficulty;
    private int problemSize;
    private int max;
    private int min;

    /**
     * 构造函数
     * @param difficulty 难度
     */
    public MathProblemBuilder(int difficulty) {
        this.difficulty = difficulty;
        //根据用户指定的年级来确定题目的难度
        switch (this.difficulty) {
            default:
            case 0:
                problemSize = 3;
                max = 100;
                min = 10;
                break;
            case 1:
            case 2:
                problemSize = 4;
                max = 100;
                min = 10;
                break;
        }
    }

    //生成一个计算题
    public MathProblem getProblem() {
        MathProblem problem, temp;
        boolean effective = false;
        float result = 0;
        do {
            //重复构建数学题并检查结果，如果结果为负数或不是整数或大于1000时重新构建
            //将参数复制给temp防止运算时变动本体
            problem = new MathProblem(problemSize, max, min, (difficulty > 1));
            temp = problem.cloneThis();
            float tempResult = problem.getResultRecursion(temp);
            if (!(tempResult < 0 || tempResult != (int)tempResult || tempResult > 1000)) {
                effective = true;
                result = tempResult;
            }
        } while (!effective);
        problem.setResult(result);
        return problem;
    }
}
